package backtrack;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author way
 * @create 2025-02-22 22:45
 */
public class _131_partition {
    List<List<String>> res = new ArrayList<>();
    LinkedList<String> path = new LinkedList<>();

    public List<List<String>> partition(String s) {

        dfs(s, 0, new StringBuilder());
        return res;
    }

    private void dfs(String s, int start, StringBuilder sb) {
        if (start == s.length()) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = start; i < s.length(); i++) {
            sb.append(s.charAt(i));
            if (isPartition(sb)) {
                path.add(sb.toString());
                dfs(s, i + 1, new StringBuilder());
                path.removeLast();
            }
        }
    }

    private boolean isPartition(StringBuilder s) {
        int left = 0;
        int right = s.length() - 1;
        while (left < right) {
            if (s.charAt(left) != s.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}
